// zd_config
package HTTP

import (
	"encoding/json"
	"logs"
	"net/http"
	"regexp"
	"strconv"
	"strings"
)

func prepare(w http.ResponseWriter, req *http.Request) (Msg string, Code int) {

	code := Success
	msg := ""
	err := req.ParseForm()
	if err != nil {
		var info interface{}
		logs.Print("req.ParseForm error", err.Error())
		code = errParseForm
		msg = err.Error()
		writeResult(w, code, msg, info)
	}
	//检查参数
	for k, v := range req.Form {
		key := k
		val := strings.Join(v, "")
		if len(val) == 0 {
			msg = key + "不能为空，请检查参数"
			code = errEmptyParameter
			break
		} else {
			msg, code = checkerr(key, val)
			if msg != "" {
				break
			}
		}
	}
	return msg, code
}

func checkerr(key string, val string) (Msg string, Code int) {
	msg := ""
	code := Success
	_, err := strconv.Atoi(val)
	switch {
	case key == "userID":
		if err != nil || len(val) != 5 {
			msg = mInvalidUserID
			code = errInvalidID
		}
	case key == "pageIndex":
		if err != nil || len(val) > 6 {
			msg = mInvalidPageIndex
			code = errInvalidPageIndex
		}
	case key == "pageSize":
		if err != nil || len(val) > 3 {
			msg = mInvalidPageSize
			code = errInvalidPageSize
		}
	case key == "GroupID":
		if err != nil || len(val) != 5 {
			msg = mInvalidGroupID
			code = errInvalidID
		}
	case key == "isManager":
		if val != "true" && val != "false" {
			msg = mInvalidBoolArg
			code = errInvalidBoolArg
		}
	case key == "password":
		reg := regexp.MustCompile("^[\\da-zA-Z-_\\.\\?\\!\\,\\@\\#\\$\\%\\^\\&\\*\\(\\)\\=\\+\\[\\]\\{\\}]{6,20}$")
		ok := reg.MatchString(val)
		if !ok {
			msg = mInvalidPassword
			code = errInvalidPassword
		}
	case key == "customInfo":
		reg := regexp.MustCompile(("^{.*\\r*\\n*}"))
		ok := reg.MatchString(val)
		if !ok {
			msg = mInvalidCustomInfo
			code = errInvalidCustomInfo
		}
		var tem interface{}
		customlist := []byte(val)
		err = json.Unmarshal(customlist, &tem)
		if err != nil {
			msg = mInvalidCustomInfo
			code = errInvalidCustomInfo
		}
	}
	return msg, code
}
